package day11;

import java.util.concurrent.locks.ReentrantLock;

//b.使用公平锁ReentrantLock实现一个线程安全的计数器，
// 多个线程同时递增计数，最后输出正确结果
public class Home2 {
    ReentrantLock lock=new ReentrantLock(true);
    static int count;
    public void test(){
        String name=Thread.currentThread().getName();
        //Home2 h2=new Home2();
        lock.lock();
        count++;
        System.out.println(name+":"+ count);
        lock.unlock();
    }
    public int get(){
        lock.lock();
        lock.unlock();
        return count;
    }
    public static void main(String[] args) {
        String name=Thread.currentThread().getName();
        Home2 h2=new Home2();
        for(int i=0;i<3;i++){
            new Thread(()->{
                for(int j=0;j<10;j++){
                    h2.test();
                }
            },"线程"+i).start();
        }
        System.out.println("最终计数结果: " + h2.get());
    }
}
